/**
 * 获取分片列表
 * @param file
 * @param chunkSize
 * @returns {*[]}
 */
export const getChunkList = (file, chunkSize) => {
    return new Array(Math.ceil(file.size / chunkSize)).fill(0).map((_, i) => {
        const start = i * chunkSize
        const end = (i + 1) * chunkSize > file.size ? file.size : (i + 1) * chunkSize
        return file.slice(start, end)
    })
}


import SparkMD5 from "spark-md5";
/**
 * 获取文件的MD5值
 * @param chunkList
 * @returns {Promise<unknown>}
 */
export const getHash = (chunkList) => {
    return new Promise((resolve) => {
        const spark = new SparkMD5.ArrayBuffer();
        const read = new FileReader()

        function _run(i) {
            if (i >= chunkList.length) {
                return resolve(spark.end())
            }
            const chunk = chunkList[i]

            read.readAsArrayBuffer(chunk)
            read.onload = () => {
                spark.append(read.result)
                _run(i + 1)
            }
        }

        _run(0)
    })
}

/**
 * 拼接对象为请求字符串
 * @param {Object} obj - 待拼接的对象
 * @returns {string} - 拼接成的请求字符串
 */
export function encodeSearchParams(obj) {
    if (!obj) return ''
    const params = []

    Object.keys(obj).forEach((key) => {
        let value = obj[key]
        // 如果值为undefined我们将其置空
        if (typeof value === 'undefined') {
            value = ''
        }
        // 去掉空串，不编码
        if (!value){
            return;
        }
        // 对于需要编码的文本（比如说中文）我们要进行编码
        params.push([key, encodeURIComponent(value)].join('='))
    })

    return params.join('&')
}

